<template>
  <el-dialog
    title="收款"
    v-model="visible"
    width="65%"
    destroy-on-close
    @closed="$emit('closed')"
  >
    <el-form
      :model="form"
      :inline="true"
      :rules="rules"
      ref="dialogForm"
      label-width="auto"
      label-position="right"
    >
      <!-- <el-form-item
        label="合同"
        prop="tractName"
        style="width: 100%"
        class="formRow"
      >
        <el-input
          v-model.number="form.tractName"
          disabled="true"
          clearable
          placeholder="请输入合同名称"
        ></el-input>
        <el-button type="primary" @click="toContractDetail" :disabled="!form.tractName>详情</el-button>
      </el-form-item> -->

      <el-form-item label="收款方式" prop="repaymentType">
        <el-select
          v-model="form.repaymentType"
          placeholder="请选择收款方式"
          style="width: 100%"
          clearable
        >
          <el-option
            v-for="item in planTypeOptions"
            :key="item.value"
            :label="item.name"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="收款账号" prop="account">
        <el-input
          v-model="form.account"
          clearable
          placeholder="请输入收款账号"
        ></el-input>
      </el-form-item>
      <el-form-item label="收款总金额" prop="account">
        <el-input
          v-model="form.totalMoney"
          clearable
          placeholder="请输入收款总金额"
          oninput="value=value.replace(/^\D*([0-9]\d*\.?\d{0,2})?.*$/,'$1')"
          @blur="form.totalMoney = $event.target.value"
          @change="changeTotalMoney"
        >
          <template v-slot:append>元</template>
        </el-input>
      </el-form-item>
      <!-- <el-form-item label="收款金额明细" prop="account" style="width: 100%">
        <div>
          实际应收款：<span style="color: green">{{
            form.actualPlanMoney ?? 0
          }}</span
          >&nbsp&nbsp&nbsp在审金额：
          <span style="color: gold">{{ money }}</span>
        </div>
      </el-form-item>
      <el-form-item
        label="单笔收款金额"
        disabled="true"
        prop="money"
        style="width: 100%"
      >
        <el-input
          v-model.number="form.money"
          clearable
          placeholder="请输入收款金额"
        >
          <template #append>元</template>
        </el-input>
      </el-form-item>
      <el-form-item
        label="抹零平账"
        disabled="true"
        prop="balancingAccounts"
        style="width: 100%"
      >
        <el-switch
          v-model="form.balancingAccounts"
          active-text="是"
          inactive-text="否"
          :active-value="1"
          :inactive-value="0"
        >
        </el-switch>
      </el-form-item> -->
      <el-form-item label="收款明细" style="width: 100%">
        <el-table
          ref="table"
          :data="planCollectsList"
          row-key="id"
          stripe
          border
        >
          <el-table-column
            prop="tractName"
            label="合同名称"
            min-width="100"
            :show-overflow-tooltip="true"
          >
          </el-table-column>
          <el-table-column
            prop="planMoney"
            label="应收金额"
            width="150"
            :show-overflow-tooltip="true"
          >
            <template #default="scope">
              <p>{{ scope.row.planMoney - scope.row.refundMoney }}元</p>
            </template>
          </el-table-column>
          <el-table-column prop="actualPlanMoney" label="实收金额" width="150">
            <template #default="scope">
              <span style="color: green"
                >{{ scope.row.actualPlanMoney ?? 0 }}元</span
              >
            </template>
          </el-table-column>
          <!-- <el-table-column label="在审金额" prop="auditMoney" width="150">
            <template #default="scope">
              <span style="color: gold">{{ scope.row.auditMoney ?? 0 }}元</span>
            </template>
          </el-table-column> -->
          <el-table-column label="单笔收款金额(元)" prop="money" width="250">
            <template #default="scope">
              <el-input-number
                :precision="2"
                v-model.number="scope.row.money"
                placeholder="请输入金额"
                @change="changeMoney($event, scope.row)"
              ></el-input-number>
            </template>
          </el-table-column>

          <el-table-column prop="num" label="抹零平账" width="200">
            <template #default="scope">
              <el-switch
                v-model="scope.row.balancingAccounts"
                active-text="是"
                inactive-text="否"
                :active-value="1"
                :inactive-value="0"
                :disabled="scope.row.auditMoney > 0"
              >
              </el-switch>
            </template>
          </el-table-column>
          <el-table-column prop="remark" label="备注" min-width="150">
            <template #default="scope">
              <el-input
                v-model="scope.row.remark"
                placeholder="请输入备注"
              ></el-input>
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>
      <el-form-item
        label="备注"
        disabled="true"
        prop="remark"
        style="width: 100%"
      >
        <el-input
          v-model="form.remark"
          clearable
          rows="3"
          type="textarea"
          placeholder="请输入备注内容"
        ></el-input>
      </el-form-item>
      <el-form-item label="附件">
        <sc-upload-file
          v-model="form.otherFileList"
          :limit="10"
          :multiple="false"
          tip="最多上传10个文件,单个文件不要超过20M"
        >
          <el-button type="primary" plain icon="el-icon-upload"
            >上传附件</el-button
          >
        </sc-upload-file>
      </el-form-item>
    </el-form>
    <el-divider />
    <!-- <check-form-item
      ref="checkFormItem"
      @setCheckConfig="setCheckConfig"
      :field="this.form"
      :checkType="checkType"
    ></check-form-item> -->
    <template #footer>
      <el-button @click="visible = false">取 消</el-button>
      <el-button type="primary" :loading="isSaveing" @click="submit()"
        >保 存</el-button
      >
    </template>
  </el-dialog>
</template>
<script>
import checkFormItem from '@/components/checkProcess/checkFormItem.vue'
import { queryTypeByDic } from '@/utils/getData'

export default {
  components: {
    checkFormItem
  },
  emits: ['success', 'closed'],
  data () {
    return {
      checkType: 5,
      visible: false,
      isSaveing: false,
      selectCustomerLoading: false,
      money: '',
      //表单数据
      form: {
        adminId: '',//跟进人id --登录时id
        departmentId: '',
        repaymentType: '', //收款方式
        account: "",  //回款账号
        remark: '',   //备注
        otherFileList: [],//附件
        planCollects: [],//收款明细
        paymentType: 1,//收款类型 1：合同收款 2：其他收款 3客户收款
        exempt: '',//是否免审
        workflowJsonList: []
      },
      planCollectsList: [],//计划收款明细列表
      planTypeOptions: [],//回款方式
      checkForm: {
        userId: '',
      },
      //验证规则
      rules: {
        repaymentType: [
          { required: true, message: '请选择收款方式', trigger: 'change' }
        ]

      }
    }
  },
  mounted () {
    this.getType()
  },

  methods: {
    // 获取计划收款详情
    async getDetail (planIds) {
      var { data } = await this.$API.finance.collectManagement.getAuditMoney.get({ planIds })
      console.log(data)
      let list = data
      let total = 0
      list.map(item => {
        item.money = item.planMoney - item.actualPlanMoney - item.refundMoney
        total += item.money
      })
      this.planCollectsList = list
      this.form.totalMoney = total
    },
    // 获取回款支付方式
    async getType () {
      this.planTypeOptions = await queryTypeByDic('payment')
    },
    // 审批流配置
    setCheckConfig (list, exempt) {
      this.form.workflowJsonList = list
      this.form.exempt = exempt
    },

    //显示
    open (list) {
      this.visible = true
      let userInfo = this.$TOOL.data.get('USER_INFO')
      this.form.departmentId = userInfo.departmentId
      this.form.adminId = userInfo.userId
      let planIds = list.map(item => item.id).join(',')
      this.getDetail(planIds)
    },

    changeTotalMoney (val) {
      let total = val
      this.planCollectsList.map(item => {
        let money = item.planMoney - item.actualPlanMoney - item.refundMoney
        total = total - money
        if (total >= 0) {
          item.money = money
        } else {
          item.money = total - (-money) <= 0 ? 0 : total - (-money)
        }
      })
    },

    changeMoney (currentValue, item) {
      if (item.money + item.actualPlanMoney > item.planMoney) {
        item.money = item.planMoney - item.actualPlanMoney - item.refundMoney
      }
      this.form.totalMoney = 0
      this.planCollectsList.forEach(item => {
        this.form.totalMoney += item.money
      })
      //console.log(this.form)
      // 计算总金额
      // if (item.money == null || item.money == 0) {
      //   this.$message.error(`请填写【${item.tractName}】的单笔收款金额`)
      // }
    },
    //表单提交方法
    submit () {

      this.$refs.dialogForm.validate(async (valid) => {
        if (valid) {
          let list = []
          // let flag = false
          this.planCollectsList.map(item => {
            // if (item.money + item.actualPlanMoney > item.planMoney) {
            //   this.$message.error("单笔金额不能大于剩余的回款金额")
            //   flag = true
            // }
            // if (item.money == null || item.money == 0) {
            //   this.$message.error(`请填写【${item.tractName}】的单笔收款金额`)
            //   flag = true
            // }
            list.push({
              contractId: item.contractId,
              id: item.id,
              money: item.money,
              planMoney: item.planMoney,
              balancingAccounts: item.balancingAccounts,
              remark: item.remark
            })
          })
          // if (flag) return

          this.form.planCollects = list

          let fileType = ''
          this.form.otherFileList.map(item => {
            if (item.url) {
              let arr = item.url.split('.')
              let type = arr[arr.length - 1]
              // fileType  1图片 2文件
              let imageType = 'jpg/png/jpeg/svg'
              if (imageType.includes(type)) {
                fileType = 1
              } else {
                fileType = 2
              }
              item.fileType = fileType
              item.fileName = item.name
            }
          })
          console.log(this.form)
          this.isSaveing = true
          let res = await this.$API.finance.plancollect.updatePlanCollectStatus.post(this.form)
          if (res.code == 200) {
            this.$emit('success')
            this.visible = false
            this.isSaveing = false
            this.$message.success("操作成功")
          }
        }
      })
    },
    toContractDetail () {
      this.$router.push({
        path: '/contract/contractManagement/contractDetail',
        query: {
          id: this.form.contractId
        }
      })
    }
  }
}
</script>
  
<style lang="scss" scoped>
.formRow {
  :deep(.el-form-item__content) {
    flex-wrap: nowrap;
    .el-button {
      margin-left: 10px;
    }
  }
}
</style>
  